from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.activity.models import Gathering
from apps.activity.activity_serializers import *
from apps.activity.pages import MyPage
import datetime


# Create your views here.
class GatheringSimpleView(ListAPIView):
    queryset = Gathering.objects.all().order_by('id')

    serializer_class = GatheringSimpleSerializer

    pagination_class = MyPage


class GatheringDetailView(RetrieveAPIView):
    queryset = Gathering.objects.all()

    serializer_class = GatheringDetailSerializer


class GatheringJoinView(APIView):

    def post(self, request, pk):

        gathering = Gathering.objects.get(id=pk)
        now_datetime = datetime.datetime.now()
        endtime = gathering.endrolltime.replace(tzinfo=None)

        # 判断当前时间是否在报名截止日期之前
        if now_datetime > endtime:
            return Response({'success': False, 'message': '报名时间已截止'})

        # 判断当前用户是否已报名
        user = request.user
        if user.is_authenticated:
            if user in gathering.users.all():
                # 判断用户是否存在于表中
                # 如果存在,删除表中用户信息,表示取消报名
                gathering.users.remove(user)
                return Response({'success': True, 'message': '取消报名成功'})
            else:
                # 如果不存在,添加,表示报名成功
                gathering.users.add(user)
                return Response({'success': True, 'message': '报名成功'})
